'use strict';

const Service = require('egg').Service;
const SysAreaModel = require('../../model/SysAreaModel');
const sysAreaModel = new SysAreaModel();

class sysAreaService extends Service {
  /**
     * 添加区域
     */
  async addArea(models) {
    return await sysAreaModel.addArea(this.app, models);
  }
  /**
     * 查询所有区域
     */
  async findAllArea() {
    return await sysAreaModel.findAllArea(this.app);
  }
  /**
     * 查询区域详情
     */
  async findAreaByCode(code) {
    return await sysAreaModel.findAreaByCode(this.app, code);
  }
  /**
     * 删除区域
     */
  async delArea(code) {
    return await sysAreaModel.delArea(this.app, code);
  }
  /**
     * 更新区域
     */
  async updateArea(code, models) {
    return await sysAreaModel.updateArea(this.app, code, models);
  }
  /*
     * 查询区域树
     */
  async querySysArea(request) {
    // 1.查询所有区域列表
    const sysAreaList = await sysAreaModel.findAllArea(this.app, request);
    if (!sysAreaList.length) {
      return [];
    }
    return sysAreaList; // this.convertAreaTree(sysAreaList, '130401');
  }

  /*
     * 将区域列表转换成区域树 数据
     * @param {[sysMenus]} sysMenusList 区域数组
     * @param {int} rootId 根目录ID
     */
  convertAreaTree(sysAreaList, code) {
    // 查找根目录
    const rootArea = sysAreaList.find(item => {
      return item.code == code;
    });
    // 区域树对象初始化
    const sysAreasTree = {
      rootArea,
    };
    sysAreasTree.rootArea.children = this.getChildrenAreas(sysAreaList, rootArea.code);
    return sysAreasTree;
  }
  /*
     * 查找子节点区域列表
     * @param {[sysAreaList]} sysAreaList 区域数组
     * @param {string} code 父节code
     */
  getChildrenAreas(sysAreaList, parentCode) {
    const _childrenSysAreaes = [];
    // 查找所有子节点
    const childrenSysAreaes = sysAreaList.filter(item => {
      return item.parent_code == parentCode;
    });
    if (childrenSysAreaes && childrenSysAreaes.length > 0) {
      for (const sysArea of childrenSysAreaes) {
        // 如果区域数据 1: 目录；2:页面  则还是有下一级区域，需要递归查找
        if (sysArea.type == 1 || sysArea.type == 2) {
            const childAreas = this.getChildrenAreas(sysAreaList, sysArea.code);
            if (childAreas.length > 0) {
              sysArea.children = childAreas;
            }
          _childrenSysAreaes.push(sysArea);
        } else {
          _childrenSysAreaes.push(sysArea);
        }
        _childrenSysAreaes.push(sysArea);
      }
    }
    return childrenSysAreaes;
  }

  async queryAllArea(){
     const sysAreaList = await sysAreaModel.findAllArea(this.app);
     return sysAreaList;
  }
}
module.exports = sysAreaService;
